package m.jclecai.com.activity.follow;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.Response.ResHotPeopleInfo;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.CustomFollowOrderDialog;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

public class CustomFollowOrderActivity extends BaseActivity {

    @BindView(R.id.iv_user_icon)
    ImageView mIvUserIcon;

    @BindView(R.id.tv_username)
    TextView mTvUsername;

    @BindView(R.id.tv_cancel_follow)
    TextView mTvCancelFollow;

    @BindView(R.id.tv_award)
    TextView mTvAward;

    @BindView(R.id.tv_follow_number)
    TextView mTvFollowNumber;

    @BindView(R.id.btn_choose_lottery)
    Button mBtnChooseLottery;

    @BindView(R.id.rb_fixed_money)
    RadioButton mRbFixedMoney;

    @BindView(R.id.rb_percent)
    RadioButton mRvPercent;

    @BindView(R.id.rg_follow_method)
    RadioGroup mRgFollowMethod;

    @BindView(R.id.et_input_number)
    EditText mEtInputNumber;

    @BindView(R.id.et_input_money)
    EditText mEtInputMoney;

    @BindView(R.id.et_input_min_money)
    EditText mEtInputMinMoney;

    @BindView(R.id.btn_pay)
    Button mBtnPay;


    @BindView(R.id.rl_follow_money)
    View mRlFollowMoney;

    @BindView(R.id.rl_follow_money_line)
    View mRlFollowMoneyLine;



    @BindView(R.id.ll_follow_percent)
    LinearLayout mLlFollowPercent;


    @BindView(R.id.et_input_max_money)
    EditText mEtMaxMoney;

    @BindView(R.id.et_input_percent)
    EditText mEtInputPercent;


    private ResHotPeopleInfo mResHotPeopleInfo;
    private CustomFollowOrderDialog mCustomFollowOrderDialog;

    private List<CustomFollowOrderDialog.LotteryBean> mChooseLottery;


    /**
     * 跟单的方式；
     */
    int mFollowType;

    public final static int  FIX_TYPE=0;
    public final static int  PERCENT_TYPE=1;
    private String mPeopleId;

    @Override
    protected int getContentView() {
        return R.layout.activity_custom_follow_order;
    }

    @Override
    protected void initView() {
        super.initView();

        setTitle("定制跟单");
        leftOptionText("");
    }

    @Override
    protected void initData() {
        super.initData();
        mCustomFollowOrderDialog = new CustomFollowOrderDialog(this);
        //初始化，按照固定金额
        mRbFixedMoney.setChecked(true);
        showMaxMoney(false);
        mPeopleId = getIntent().getStringExtra(PEOPLE_ID);
        requestData();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mCustomFollowOrderDialog.setListener(new CustomFollowOrderDialog.OnSureClickListener() {

            @Override
            public void onSureClick(List<CustomFollowOrderDialog.LotteryBean> mData) {
                //这里我们将获取用户选中的彩种；
                mChooseLottery = mData;
                String lotteryName="";
                for (CustomFollowOrderDialog.LotteryBean lotteryBean : mData) {
                    lotteryName+=lotteryBean.getLotteryName()+",";
                }
                if(!TextUtils.isEmpty(lotteryName)){
                    lotteryName=lotteryName.substring(0,lotteryName.length()-1);
                     mBtnChooseLottery.setText(lotteryName);
                }else{
                    mBtnChooseLottery.setText("点击选择彩种");
                }
            }
        });


        mRgFollowMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                   case R.id.rb_fixed_money:
                       //按照固定金额
                       mFollowType=FIX_TYPE;
                       showMaxMoney(false);
                       break;
                   case R.id.rb_percent:
                       //按照百分比；
                        mFollowType=PERCENT_TYPE;
                       showMaxMoney(true);
                       break;
                }
            }
        });
    }

    /**
     * 是否显示跟单的最大金额；
     * @param isShowMaxMoney true表示显示，false表示不显示
     */
    private void showMaxMoney(boolean isShowMaxMoney) {
        //固定金额的输入框
        mRlFollowMoney.setVisibility(isShowMaxMoney?View.GONE:View.VISIBLE);
        mRlFollowMoneyLine.setVisibility(isShowMaxMoney?View.GONE:View.VISIBLE);
        //百分比的输入框；
        mLlFollowPercent.setVisibility(isShowMaxMoney? View.VISIBLE:View.GONE);
    }

    private void requestData() {

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("id", mPeopleId);
        HttpManager.postAsyn(Constant_Url.HOT_PEOPLE_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常!");
            }

            @Override
            public void onResponse(String response) {
                if (!TextUtils.isEmpty(response)) {
                    mResHotPeopleInfo = FastOk.get(response, ResHotPeopleInfo.class);
                    if ("0".equals(mResHotPeopleInfo.getStatus())) {

                        updateUI();
                    } else {
                        DisPlay(mResHotPeopleInfo.getMessage());
                    }
                } else {
                    DisPlay("网络异常!");
                }
            }
        }, paramsMap);

    }

    private void updateUI() {
        mTvUsername.setText(mResHotPeopleInfo.getUsername());
        Glide.with(this).load(mResHotPeopleInfo.getUser_face()).into(mIvUserIcon);
        mTvAward.setText(mResHotPeopleInfo.getWinmoneys_total());
        mTvFollowNumber.setText(mResHotPeopleInfo.getFans()+"");
    }

    @OnClick(R.id.tv_cancel_follow)
    public void cancelCustom(){
        //这里是取消定制,某某个红人的所有的订单；

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user",PreferenceUtil.getUserName(this));
        paramsMap.put("password",PreferenceUtil.getPassword(this));
        paramsMap.put("id","1");

        HttpManager.postAsyn(Constant_Url.CANCEL_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络连接异常!!!");
            }

            @Override
            public void onResponse(String response) {
                //这里我们要做的一个操作就是看看是否成功了。
            }
        },paramsMap);
    }

    @OnClick(R.id.btn_choose_lottery)
    public  void chooseLottery(){
        mCustomFollowOrderDialog.show();
    }

    @OnClick(R.id.btn_pay)
    public void follow(){
        //这里我们将定制跟单
        String lotteryName = mBtnChooseLottery.getText().toString();
        //金额低于多少停止投注
        String inputMinMoney = mEtInputMinMoney.getText().toString();
        //认购方案个数
        String inputNumber=mEtInputNumber.getText().toString();
        //每个认购方案的金额
        String inputMoney = mEtInputMoney.getText().toString();

        //跟单的百分比
        String inputPercent = mEtInputPercent.getText().toString();
        String maxMoney = mEtMaxMoney.getText().toString();

        //检查数据的有效性：
        if("点击选择彩种".equals(lotteryName)){
            DisPlay("至少选择一个彩种");
            return;
        }
        if(TextUtils.isEmpty(inputNumber)){
            DisPlay("至少选择选择一个认购方案");
            return;
        }
        if(mFollowType == FIX_TYPE){

            if(TextUtils.isEmpty(inputMoney)){
                DisPlay("每个方案认购金额必须大于0");
                return;
            }

        }else if(mFollowType == PERCENT_TYPE){

            if (TextUtils.isEmpty(inputPercent)) {
                DisPlay("跟单百分比需要大于0.1%");
                return;
            }
        /*    if (TextUtils.isEmpty(maxMoney)) {
                DisPlay("最大跟单金额需要大于1元");
                return;
            }*/

        }

        String money=mFollowType==0?inputMoney:inputPercent;

        doCustom(mPeopleId,mFollowType+"",inputNumber,money,inputMinMoney, lotteryNameToType());
    }

    public void doCustom(String id,String offlag,String tnum,String money,String balance,String type){

        showDialog();

        final HashMap<String, String> pararmsMap = new HashMap<>();
        pararmsMap.put("user", PreferenceUtil.getUserName(this));
        pararmsMap.put("password",PreferenceUtil.getPassword(this));
        pararmsMap.put("id",id);
        pararmsMap.put("oflag",offlag);
        pararmsMap.put("tnum",tnum);
        pararmsMap.put("money",money);
        pararmsMap.put("balance",balance);
        pararmsMap.put("type",type);

        HttpManager.postAsyn(Constant_Url.ADD_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络连接异常!!!");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                try {
                    if (!TextUtils.isEmpty(response)) {

                        ProofBean proofBean = FastOk.get(response, ProofBean.class);
                        if(proofBean!=null && "0".equals(proofBean.getStatus())){
                            //定制成功
                            DisPlay("定制成功！！！");
                        }else{
                            if (proofBean != null) {
                                DisPlay(proofBean.getMessage());
                            }
                        }

                    }else{
                        DisPlay("网络连接异常!!!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络连接异常!!!");
                }
            }
        },pararmsMap);
    }


    /**
     * 取消红人的定制
     * @param id 红人的id
     * @param type 彩种；
     */
    public void doCancelCustom(String id,String type){

        showDialog();

        final HashMap<String, String> pararmsMap = new HashMap<>();
        pararmsMap.put("user", PreferenceUtil.getUserName(this));
        pararmsMap.put("password",PreferenceUtil.getPassword(this));
        pararmsMap.put("id",id);
        pararmsMap.put("type",type);

        HttpManager.postAsyn(Constant_Url.CANCEL_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络连接异常!!!");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if(proofBean!=null && "0".equals(proofBean.getStatus())){
                        //取消成功
                    }else{
                        if (proofBean != null) {
                            DisPlay(proofBean.getMessage());
                        }
                    }

                }else{
                    DisPlay("网络连接异常!!!");
                }
            }
        },pararmsMap);
    }




    /**
     *
     * 修改红人的定制跟单
     * @param id 定制的id;
     * @param offlag  定制类型
     * @param tnum 定制次数
     * @param money 每次认购金额，百分比
     * @param balance 认购金额上限
     * @param type  定制彩种
     * @param israndom 操作类型【0表示添加，1表示修改】
     */
    public void doEditCustom(String id,String offlag,String tnum,String money,String balance,String type,String israndom){

        showDialog();
        final HashMap<String, String> pararmsMap = new HashMap<>();
        pararmsMap.put("user", PreferenceUtil.getUserName(this));
        pararmsMap.put("password",PreferenceUtil.getPassword(this));
        pararmsMap.put("id",id);
        pararmsMap.put("oflag",offlag);
        pararmsMap.put("tnum",tnum);
        pararmsMap.put("money",money);
        pararmsMap.put("balance",balance);
        pararmsMap.put("type",type);
        pararmsMap.put("israndom",israndom);

        HttpManager.postAsyn(Constant_Url.EDIT_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络连接异常!!!");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if(proofBean!=null && "0".equals(proofBean.getStatus())){
                        //定制成功
                    }else{
                        if (proofBean != null) {
                            DisPlay(proofBean.getMessage());
                        }
                    }

                }else{
                    DisPlay("网络连接异常!!!");
                }
            }
        },pararmsMap);
    }

    public String[] type={};
    public String[] typeStr={
            "双色球","大乐透", "福彩3D",
            "排列三","排列"
    };

    public String lotteryNameToType(){
        String type="";
        for (CustomFollowOrderDialog.LotteryBean lotteryBean : mChooseLottery) {
            type=lotteryBean.type+",";
        }
        type=type.substring(0,type.length()-1);
        return type;
    }


    public static final String PEOPLE_ID="peopleId";

    public static Intent getIntent(Context context,String peopleId){
        Intent intent = new Intent(context, CustomFollowOrderActivity.class);
        intent.putExtra(PEOPLE_ID,peopleId);
        return intent;
    }

}
